<script setup lang="ts">
import * as monaco from "monaco-editor";
import { onMounted, watch } from "vue";
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import { useDark } from '@vueuse/core'
const isDark = useDark()
window.MonacoEnvironment = {
    getWorker(_: string, label: string) {
        if (label === 'json') {
            return new jsonWorker()
        }
        return new EditorWorker()
    },
}
const props = defineProps(['modelValue', "language"]);
const emit = defineEmits(['update:modelValue']);
onMounted(() => {
    const monacoEditor: any = monaco.editor.create(
        document.getElementById("monaco-editor") as HTMLElement,
        {
            automaticLayout: true,
            language: props.language,
            value: props.modelValue,
            readOnly: false,
            theme: isDark.value ? 'vs-dark' : "vs",
            fontSize: 14,
            lineHeight: 24,
            extraEditorClassName: "",
            minimap: { enabled: false },
            formatOnType: true,
            formatOnPaste: true,
            autoClosingBrackets: 'always',
            autoClosingDelete: 'always',
            autoClosingOvertype: 'always',
            autoClosingQuotes: 'always',
            codeLens: false,
            contextmenu: true,
            columnSelection: true,
            autoSurround: 'never',
            copyWithSyntaxHighlighting: true,
            cursorBlinking: 'smooth',
            cursorSmoothCaretAnimation: 'on',
            cursorStyle: 'line',
            cursorSurroundingLines: 0,
            cursorSurroundingLinesStyle: 'all',
            cursorWidth: 2,
            scrollbar: {
                verticalScrollbarSize: 10,
                horizontalScrollbarSize: 10,
                arrowSize: 10,
            },
            folding: false,
            links: false,
            overviewRulerBorder: false,
            renderLineHighlight: 'gutter',
            scrollBeyondLastLine: false,
            lineNumbers: 'on',
            lineNumbersMinChars: 3,
            roundedSelection: true,
            autoIndent: 'full',
        }
    );
    monacoEditor.onDidChangeModelContent(() => {
        emit("update:modelValue", monacoEditor.getValue());
    });
    monacoEditor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
        console.log('Ctrl + S');
        monacoEditor.getAction('editor.action.formatDocument').run();
    });
});
watch(() => isDark.value, () => {
    monaco.editor.setTheme(isDark.value ? 'vs-dark' : "vs");
});
</script>

<template>
    <div class="flex flex-col h-full">
        <div class="flex-1 h-0" id="monaco-editor"></div>
    </div>
</template>
<style scoped></style>